<!-- 右侧悬浮按钮 -->
<template>
    <div class="kefu-affix">
        <el-tooltip placement="right" effect="light" :visible="kefu.state.newMessage.show" v-if="kefu.state.system.switch && kefu.state.affix.show">
            <template #content>
                <div @click="onClickAffix">{{ truncate(`${kefu.state.newMessage.content}`) }}</div>
            </template>
            <img
                :style="{ top: state.affixTop, left: state.affixLeft }"
                :src="affixImg"
                class="kefu-button"
                alt="客服浮标"
                @mousedown="onMousedownAffix"
                @mouseup="onMouseupAffix"
                @click="onClickAffix"
            />
        </el-tooltip>

        <!-- 用户会话框 -->
        <UserDialog v-if="kefu.state.system.switch" />

        <!-- 访客邀请对话框 -->
        <transition name="el-zoom-in-center">
            <div
                v-if="kefu.state.invitation.show"
                class="invitation-box"
                :style="{
                    background: 'url(' + fullUrl(kefu.config!.auto_invitation_bg) + ')',
                    backgroundSize: '100% 100%',
                }"
            >
                <div class="close" @click="kefu.hideInvitation()">&times;</div>
                <div class="bottom-button">
                    <div class="later" @click="kefu.hideInvitation()">稍后再说</div>
                    <div class="consulting" @click="onClickAffix">现在咨询</div>
                </div>
            </div>
        </transition>
    </div>
</template>

<script setup lang="ts">
import { debounce, truncate } from 'lodash-es'
import { onMounted, reactive } from 'vue'
import { fullUrl } from '@/utils/common'
import { useEventListener } from '@vueuse/core'
import { Local } from '@/utils/storage'
import { KEFU_BUTTON_COORDINATE } from './store'
import keFu from '@/components/kefu/index'
import UserDialog from './components/userDialog.vue'
import useCurrentInstance from '@/utils/useCurrentInstance'
import affixImg from '@/assets/kefu/affix-1.png'
const { proxy } = useCurrentInstance()
const kefu = new keFu()
proxy.kefu = kefu

const state = reactive({
    affixTop: '80%',
    affixLeft: 'unset',
})

const staticObj: {
    startX: number
    startY: number
    affixX: number
    affixY: number
    moveAffixFlag: boolean
    clickAffixFlag: boolean
} = {
    startX: 0,
    startY: 0,
    affixX: 0,
    affixY: 0,
    moveAffixFlag: false,
    clickAffixFlag: false,
}

/**
 * 浮标鼠标按下事件
 */
const onMousedownAffix = (e: MouseEvent) => {
    staticObj.clickAffixFlag = false
    staticObj.moveAffixFlag = true

    kefu.hideNewMessagePopover()
    document.onselectstart = () => false
    document.ondragstart = () => false
    document.querySelectorAll('iframe').forEach((item) => {
        item.style.pointerEvents = 'none'
    })

    staticObj.affixY = e.pageY - (e.target as HTMLElement).offsetTop
    staticObj.affixX = e.pageX - (e.target as HTMLElement).offsetLeft

    // 初始按钮位置
    staticObj.startX = (e.target as HTMLElement).offsetTop
    staticObj.startY = (e.target as HTMLElement).offsetLeft
}

/**
 * 浮标鼠标移动事件
 */
const onMousemoveAffix = (e: MouseEvent) => {
    if (!staticObj.moveAffixFlag) return
    const x = e.pageX - staticObj.affixX
    const y = e.pageY - staticObj.affixY

    const offsetTop = (e.target as HTMLElement).offsetTop
    const offsetLeft = (e.target as HTMLElement).offsetLeft

    if (Math.abs(staticObj.startY - offsetLeft) + Math.abs(staticObj.startX - offsetTop) > 7) {
        staticObj.clickAffixFlag = true
    }

    Local.set(KEFU_BUTTON_COORDINATE, [y, x])

    state.affixTop = y + 'px'
    state.affixLeft = x + 'px'
}

/**
 * 浮标鼠标松开事件
 */
const onMouseupAffix = () => {
    document.onselectstart = null
    document.ondragstart = null
    document.querySelectorAll('iframe').forEach((item) => {
        item.style.pointerEvents = 'auto'
    })
    staticObj.moveAffixFlag = false
}

/**
 * 浮标点击事件
 */
const onClickAffix = () => {
    if (staticObj.clickAffixFlag) return
    kefu.onConversation()
}

onMounted(() => {
    // 在 document 监听 mousemove 事件以保证性能
    document.addEventListener('mousemove', onMousemoveAffix)

    // 恢复按钮位置
    let kefuKuttonCoordinate = Local.get(KEFU_BUTTON_COORDINATE)
    if (kefuKuttonCoordinate) {
        if (kefuKuttonCoordinate[0] && kefuKuttonCoordinate[1] && document.documentElement.clientWidth > parseInt(kefuKuttonCoordinate[1])) {
            state.affixTop = kefuKuttonCoordinate[0] + 'px'
            state.affixLeft = kefuKuttonCoordinate[1] + 'px'
        }
    }

    useEventListener(
        window,
        'resize',
        debounce(() => {
            console.log('窗口大小发生变化，已恢复按钮至初始位置')
            state.affixTop = '80%'
            state.affixLeft = 'unset'
            kefu.hideNewMessagePopover()
        }, 200)
    )

    useEventListener(
        window,
        'scroll',
        debounce(() => {
            kefu.hideNewMessagePopover()
        }, 200)
    )
})
</script>

<style lang="scss">
@keyframes shake-horizontal {
    2% {
        transform: translate(-6px, 0) rotate(0);
    }
    4% {
        transform: translate(9px, 0) rotate(0);
    }
    6% {
        transform: translate(-6px, 0) rotate(0);
    }
    8% {
        transform: translate(-2px, 0) rotate(0);
    }
    10% {
        transform: translate(8px, 0) rotate(0);
    }
    12% {
        transform: translate(-6px, 0) rotate(0);
    }
    14% {
        transform: translate(0px, 0) rotate(0);
    }
    16% {
        transform: translate(-1px, 0) rotate(0);
    }
    18% {
        transform: translate(9px, 0) rotate(0);
    }
    20% {
        transform: translate(-4px, 0) rotate(0);
    }
    22% {
        transform: translate(-6px, 0) rotate(0);
    }
    24% {
        transform: translate(-5px, 0) rotate(0);
    }
    26% {
        transform: translate(-9px, 0) rotate(0);
    }
    28% {
        transform: translate(-4px, 0) rotate(0);
    }
    30% {
        transform: translate(2px, 0) rotate(0);
    }
    32% {
        transform: translate(0px, 0) rotate(0);
    }
    34% {
        transform: translate(0px, 0) rotate(0);
    }
    36% {
        transform: translate(1px, 0) rotate(0);
    }
    38% {
        transform: translate(-1px, 0) rotate(0);
    }
    40% {
        transform: translate(0px, 0) rotate(0);
    }
    42% {
        transform: translate(1px, 0) rotate(0);
    }
    44% {
        transform: translate(-8px, 0) rotate(0);
    }
    46% {
        transform: translate(-8px, 0) rotate(0);
    }
    48% {
        transform: translate(8px, 0) rotate(0);
    }
    50% {
        transform: translate(3px, 0) rotate(0);
    }
    52% {
        transform: translate(-4px, 0) rotate(0);
    }
    54% {
        transform: translate(3px, 0) rotate(0);
    }
    56% {
        transform: translate(-8px, 0) rotate(0);
    }
    58% {
        transform: translate(0px, 0) rotate(0);
    }
    60% {
        transform: translate(-9px, 0) rotate(0);
    }
    62% {
        transform: translate(-4px, 0) rotate(0);
    }
    64% {
        transform: translate(2px, 0) rotate(0);
    }
    66% {
        transform: translate(1px, 0) rotate(0);
    }
    68% {
        transform: translate(-7px, 0) rotate(0);
    }
    70% {
        transform: translate(-8px, 0) rotate(0);
    }
    72% {
        transform: translate(5px, 0) rotate(0);
    }
    74% {
        transform: translate(-7px, 0) rotate(0);
    }
    76% {
        transform: translate(6px, 0) rotate(0);
    }
    78% {
        transform: translate(-6px, 0) rotate(0);
    }
    80% {
        transform: translate(4px, 0) rotate(0);
    }
    82% {
        transform: translate(-8px, 0) rotate(0);
    }
    84% {
        transform: translate(-3px, 0) rotate(0);
    }
    86% {
        transform: translate(2px, 0) rotate(0);
    }
    88% {
        transform: translate(-1px, 0) rotate(0);
    }
    90% {
        transform: translate(1px, 0) rotate(0);
    }
    92% {
        transform: translate(-5px, 0) rotate(0);
    }
    94% {
        transform: translate(-8px, 0) rotate(0);
    }
    96% {
        transform: translate(0px, 0) rotate(0);
    }
    98% {
        transform: translate(-8px, 0) rotate(0);
    }
    0%,
    100% {
        transform: translate(0, 0) rotate(0);
    }
}
.ba-kefu-shake {
    transform-origin: center center;
    animation-name: shake-horizontal;
    animation-duration: 100ms;
    animation-timing-function: ease-in-out;
    animation-iteration-count: 4;
}
</style>

<style scoped lang="scss">
.kefu-button {
    display: block;
    position: fixed;
    top: 80%;
    right: 50px;
    width: 50px;
    height: 50px;
    z-index: 1000;
    animation: pulse 2s infinite;
    border-radius: 50%;
    user-select: none;
    cursor: pointer;
}
.invitation-box {
    position: fixed;
    width: 400px;
    height: 200px;
    top: calc(50% - 100px);
    left: calc(50% - 200px);
    border-radius: 5px;
    z-index: 1200;
    box-shadow: 0 0 10px rgba(135, 137, 138, 0.27);
    .close {
        color: #999;
        font-size: 24px;
        position: absolute;
        line-height: 24px;
        right: 4px;
        cursor: pointer;
    }
    .close:hover {
        color: #222;
    }
    .bottom-button {
        position: absolute;
        bottom: 13px;
        right: 10px;
        display: flex;
    }
    .bottom-button div {
        border: 1px solid #fff;
        padding: 3px 10px;
        border-radius: 2px;
        font-size: 12px;
        line-height: 20px;
    }
    .bottom-button .later {
        color: var(--el-color-primary);
        background: #fff;
        margin-right: 10px;
        cursor: pointer;
    }
    .bottom-button .consulting {
        color: #fff;
        background: var(--el-color-primary);
        border-color: var(--el-color-primary);
        cursor: pointer;
    }
}

@media screen and (max-width: 1000px) {
    .invitation-box {
        width: 300px;
        height: 150px;
        top: calc(50% - 75px);
        left: calc(50% - 150px);
    }
}

@-webkit-keyframes pulse {
    0% {
        -webkit-box-shadow: 0 0 0 0 rgba(13, 130, 255, 0.4);
    }
    70% {
        -webkit-box-shadow: 0 0 0 10px rgba(13, 130, 255, 0);
    }
    100% {
        -webkit-box-shadow: 0 0 0 0 rgba(13, 130, 255, 0);
    }
}
@keyframes pulse {
    0% {
        -moz-box-shadow: 0 0 0 0 rgba(13, 130, 255, 0.4);
        box-shadow: 0 0 0 0 rgba(13, 130, 255, 0.4);
    }
    70% {
        -moz-box-shadow: 0 0 0 10px rgba(13, 130, 255, 0);
        box-shadow: 0 0 0 10px rgba(13, 130, 255, 0);
    }
    100% {
        -moz-box-shadow: 0 0 0 0 rgba(13, 130, 255, 0);
        box-shadow: 0 0 0 0 rgba(13, 130, 255, 0);
    }
}
</style>
